<template>
  <el-container>
    <el-card class="info-card" shadow="hover">
      <div class="title">
        <p>个人信息管理</p>
      </div>
      <div class="info-row">
        <el-avatar :src="user.userimage" class="avatar" @click="showAvatarCard = true"></el-avatar>
      </div>
      <br>
      <div class="info-row">
        <span v-if="!isEditingUsername" class="info-label">用户名: {{ user.username }}</span>
        <div v-if="isEditingUsername" class="edit-row">
          <span class="edit-label">用户名:</span>
          <el-input v-model="user.username" placeholder="请输入用户名" class="el-input"></el-input>
        </div>
        <el-button v-if="!isEditingUsername" type="warning" @click="isEditingUsername = true">编辑</el-button>
        <el-button v-if="isEditingUsername" type="success" @click="saveUsername">保存</el-button>
      </div>
      <br>
      <div class="info-row">
        <span class="info-label">学号: {{ user.usernum }}</span>
        <el-button type="danger" plain disabled>编辑</el-button>
      </div>
      <br>
      <div class="info-row">
        <span v-if="!isEditingPhone" class="info-label">手机号码: {{ user.userPhone }}</span>
        <div v-if="isEditingPhone" class="edit-row">
          <span class="edit-label">手机号码:</span>
          <el-input v-model="user.userPhone" placeholder="请输入手机号码" class="el-input"></el-input>
        </div>
        <el-button v-if="!isEditingPhone" type="warning" @click="isEditingPhone = true">编辑</el-button>
        <el-button v-if="isEditingPhone" type="success" @click="saveUserPhone">保存</el-button>
      </div>
      <br>
      <div class="info-row">
        <span v-if="!isEditingEmail" class="info-label">邮箱: {{ user.useremail }}</span>
        <div v-if="isEditingEmail" class="edit-row">
          <span class="edit-label">邮箱:</span>
          <el-input v-model="user.useremail" placeholder="请输入邮箱" class="el-input"></el-input>
        </div>
        <el-button v-if="!isEditingEmail" type="warning" @click="isEditingEmail = true">编辑</el-button>
        <el-button v-if="isEditingEmail" type="success" @click="saveUserEmail">保存</el-button>
      </div>
      <br>
      <div class="info-row">
        <el-button @click="showPasswordCard = true" class="center-button">修改密码</el-button>
      </div>
    </el-card>
    <el-card v-if="showAvatarCard" class="avatar-card">
      <el-form-item label="当前头像">
        <el-avatar :src="user.userimage" class="avatar"></el-avatar>
      </el-form-item>
      <el-form-item label="更改头像">
        <el-upload
          action="http://localhost:8000/UserController/updateUserImage"
          list-type="picture-card"
          :show-file-list="false"
          :data="{ userID: user.userID }"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="saveUserImage"
          :with-credentials="true"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button @click="showAvatarCard = false">取消</el-button>
      </el-form-item>
    </el-card>
    <el-card v-if="showPasswordCard" class="password-card">
      <el-form-item label="旧密码">
        <el-input v-model="oldPassword" placeholder="旧密码" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码">
        <el-input v-model="newPassword" placeholder="新密码" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="changePassword">保存</el-button>
        <el-button @click="showPasswordCard = false">取消</el-button>
      </el-form-item>
    </el-card>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const user = ref({
  userimage: '',
  username: '',
  usernum: '',
  userPhone: '',
  useremail: '' // 新增邮箱字段
});

const oldPassword = ref('');
const newPassword = ref('');

const isEditingUsername = ref(false);
const isEditingPhone = ref(false);
const isEditingEmail = ref(false); // 新增邮箱编辑状态
const showAvatarCard = ref(false);
const showPasswordCard = ref(false);

const fetchUserData = () => {
  axios.get('http://localhost:8000/UserController/getUser', { withCredentials: true })
    .then(response => {
      console.log('接收到的用户数据:', response.data);
      user.value = response.data;
      if (user.value.userimage) {
        user.value.userimage = 'data:image/jpeg;base64,' + user.value.userimage;
      }
    })
    .catch(error => {
      console.error('获取用户数据失败:', error);
    });
};

const handlePictureCardPreview = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    user.value.userimage = e.target.result; // 保存为 Base64 编码
  };
  reader.readAsDataURL(file.raw);
};

const handleRemove = (file, fileList) => {
  console.log('文件已移除:', file, fileList);
  user.value.userimage = '';
};

const saveUserImage = (response, file) => {
  console.log('头像已更新:', response);
  // 立即更新用户头像的显示
  user.value.userimage = URL.createObjectURL(file.raw);
  showAvatarCard.value = false;
  ElMessage.success('头像已更新');
};

const saveUsername = () => {
  axios.post('http://localhost:8000/UserController/updateUser', {
    username: user.value.username
  }, { withCredentials: true })
  .then(response => {
    console.log('用户名已更新:', response.data);
    isEditingUsername.value = false;
    ElMessage.success('用户名已更新');
  })
  .catch(error => {
    console.error('更新用户名失败:', error);
    ElMessage.error('更新用户名失败');
  });
};

const saveUserPhone = () => {
  axios.post('http://localhost:8000/UserController/updateUser', {
    userPhone: user.value.userPhone
  }, { withCredentials: true })
  .then(response => {
    console.log('手机号已更新:', response.data);
    isEditingPhone.value = false;
    ElMessage.success('手机号已更新');
  })
  .catch(error => {
    console.error('更新手机号失败:', error);
    ElMessage.error('更新手机号失败');
  });
};

const saveUserEmail = () => {
  axios.post('http://localhost:8000/UserController/updateUser', {
    useremail: user.value.useremail
  }, { withCredentials: true })
  .then(response => {
    console.log('邮箱已更新:', response.data);
    isEditingEmail.value = false;
    ElMessage.success('邮箱已更新');
  })
  .catch(error => {
    console.error('更新邮箱失败:', error);
    ElMessage.error('更新邮箱失败');
  });
};

const changePassword = () => {
  if (newPassword.value.length < 6) {
    ElMessage.error('新密码长度不能少于6位');
    return;
  }
  axios.post('http://localhost:8000/UserController/updatePassword', {
    oldPassword: oldPassword.value,
    newPassword: newPassword.value
  }, { withCredentials: true })
  .then(response => {
    console.log('密码已更新:', response.data);
    oldPassword.value = '';
    newPassword.value = '';
    showPasswordCard.value = false;
    ElMessage.success('密码已更新');
  })
  .catch(error => {
    console.error('更新密码失败:', error);
    ElMessage.error('更新密码失败');
  });
};

onMounted(() => {
  fetchUserData();
});
</script>

<style scoped>
.form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  cursor: pointer;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
}
.info-card {
  opacity: 0.6;
  padding: 20px;
  position: absolute;
  top: 20%;
  left: 30%;
  right: 30%;
  bottom: 20%;
}
.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px; 
}
.edit-row {
  display: flex;
  align-items: center;
}
.edit-label {
  margin-right: 10px;
  font-size: 1.5em; /* 增大字体 */
}
.info-label {
  font-size: 1.5em; /* 增大字体 */
}
.center-button {
  display: block;
  margin: 0 auto;
}
.avatar-card, .password-card {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  padding: 20px;
}

.el-input{
  width: 50%; 
}
</style>
